{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "d:\\softwares\\python\\lib\\site-packages\\tqdm\\auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n",
      "  from .autonotebook import tqdm as notebook_tqdm\n"
     ]
    }
   ],
   "source": [
    "from transformers import BertTokenizer, BertModel"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 截断案例"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Some weights of the model checkpoint at bert-base-chinese were not used when initializing BertModel: ['cls.predictions.transform.LayerNorm.weight', 'cls.seq_relationship.weight', 'cls.predictions.transform.dense.bias', 'cls.predictions.transform.dense.weight', 'cls.predictions.bias', 'cls.predictions.transform.LayerNorm.bias', 'cls.seq_relationship.bias', 'cls.predictions.decoder.weight']\n",
      "- This IS expected if you are initializing BertModel from the checkpoint of a model trained on another task or with another architecture (e.g. initializing a BertForSequenceClassification model from a BertForPreTraining model).\n",
      "- This IS NOT expected if you are initializing BertModel from the checkpoint of a model that you expect to be exactly identical (initializing a BertForSequenceClassification model from a BertForSequenceClassification model).\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[101, 2769, 1599, 3614, 5632, 4197, 6427, 6241, 1905, 102]\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'[CLS] 我 喜 欢 自 然 语 言 处 [SEP]'"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 模型名字，https://huggingface.co/google-bert/bert-base-chinese\n",
    "# 这里使用bert-base-chinese\n",
    "model_name = \"bert-base-chinese\"\n",
    "\n",
    "# 加载tokenizer和model\n",
    "tokenizer = BertTokenizer.from_pretrained(model_name)\n",
    "model = BertModel.from_pretrained(model_name)\n",
    "\n",
    "# 演示Tokenizer\n",
    "output = tokenizer.encode(\n",
    "    # 待编码的文本\n",
    "    text='我喜欢自然语言处理，因为它很有趣',\n",
    "    # 设置文本的最大长度\n",
    "    max_length=10,\n",
    "    # 设置如果超过最大长度，则截断\n",
    "    truncation=True,\n",
    "    # 如果长度不够，则自动填充到max_length\n",
    "    padding='max_length',\n",
    "    # 设置为None，则指定返回list类型\n",
    "    return_tensors=None,\n",
    ")\n",
    "print(output) # [101, 2769, 1599, 3614, 5632, 4197, 6427, 6241, 1905, 102]\n",
    "tokenizer.decode(output) # '[CLS] 我 喜 欢 自 然 语 言 处 [SEP]'，这里编码成了bert模型能处理的方式，包括[CLS][SEP]等特殊符号\n",
    "# 在 BERT模型中，[CLS] 和 [PAD] 是两个特殊的标记，用于在输入文本中传达额外的信息\n",
    "# [CLS] 标记是 BERT 模型输入序列的特殊起始标记，通常用于表示整个句子的语义信息\n",
    "# [PAD] 标记用于在输入序列中进行填充，由于 BERT 模型要求输入序列的长度是固定的，因此如果输入的文本长度不足，需要通过在文本末尾添加 [PAD] 标记来进行填充，以保证所有输入序列的长度一致。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 填充案例"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Some weights of the model checkpoint at bert-base-chinese were not used when initializing BertModel: ['cls.predictions.transform.LayerNorm.weight', 'cls.seq_relationship.weight', 'cls.predictions.transform.dense.bias', 'cls.predictions.transform.dense.weight', 'cls.predictions.bias', 'cls.predictions.transform.LayerNorm.bias', 'cls.seq_relationship.bias', 'cls.predictions.decoder.weight']\n",
      "- This IS expected if you are initializing BertModel from the checkpoint of a model trained on another task or with another architecture (e.g. initializing a BertForSequenceClassification model from a BertForPreTraining model).\n",
      "- This IS NOT expected if you are initializing BertModel from the checkpoint of a model that you expect to be exactly identical (initializing a BertForSequenceClassification model from a BertForSequenceClassification model).\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[101, 2769, 1599, 3614, 102, 0, 0, 0, 0, 0]\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'[CLS] 我 喜 欢 [SEP] [PAD] [PAD] [PAD] [PAD] [PAD]'"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model_name = \"bert-base-chinese\"\n",
    "\n",
    "tokenizer = BertTokenizer.from_pretrained(model_name)\n",
    "model = BertModel.from_pretrained(model_name)\n",
    "\n",
    "# 演示Tokenizer\n",
    "output = tokenizer.encode(\n",
    "    text='我喜欢',\n",
    "    max_length=10,\n",
    "    truncation=True,\n",
    "    # 如果长度不够，则自动填充到max_length\n",
    "    padding='max_length',\n",
    "    return_tensors=None,\n",
    ")\n",
    "print(output) # [101, 2769, 1599, 3614, 102, 0, 0, 0, 0, 0]\n",
    "tokenizer.decode(output) # '[CLS] 我 喜 欢 [SEP] [PAD] [PAD] [PAD] [PAD] [PAD]'，[PAD]代表填充"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
